package com.khyr.filter;

import com.alibaba.fastjson.JSON;
import com.khyr.whiteurl.WhiteUrl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author ：Zhang
 * @date ：Created in 2025/3/10 19:17
 * @description：电脑端登录过滤器
 * @modified By：
 * @version: 1.0
 */
@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Autowired
    private WhiteUrl whiteUrl;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("进入过滤器");
        //1. 获取request对象和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2. 获取请求路径
        String path = request.getURI().getPath();
        if(whiteUrl.getUrls().contains(path)){
            System.out.println("白名单"+path);
            return chain.filter(exchange);
        }else{
            System.out.println("进入登录过滤器");
            //3. 获取请求头中的token
            String token = request.getHeaders().getFirst("token");
            //4. 判断token是否为null或缓存是否存在
            if(token!=null && redisTemplate.hasKey("user::login::"+token)){
                // 刷新过期时间
                redisTemplate.expire("user::login::" + token, 30, TimeUnit.MINUTES);
                return chain.filter(exchange);
            }
        }
        Map<String,Object> map = new HashMap<>();
        map.put("msg","请先登录");
        map.put("code",401);

        //3.3作JSON转换
        byte[] bytes = JSON.toJSONString(map).getBytes(StandardCharsets.UTF_8);

        //3.4调用bufferFactory方法,生成DataBuffer对象
        DataBuffer buffer = response.bufferFactory().wrap(bytes);

        //4.调用Mono中的just方法,返回要写给前端的JSON数据
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
